package com.zxmr.webclient.action;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zxmr.domain.account.AccountStatus;
import com.zxmr.domain.account.AccountType;
import com.zxmr.domain.account.Company;
import com.zxmr.domain.account.User;
import com.zxmr.domain.service.CompanyService;
import com.zxmr.webclient.action.dto.CompanyRegister;
import com.zxmr.webclient.action.view.FailedJSONView;
import com.zxmr.webclient.action.view.JSONView;
import com.zxmr.webclient.action.view.SuccessJSONView;

@Controller
public class CompanyController {

	@RequestMapping(value = "/company/register", method = RequestMethod.POST)
	public @ResponseBody JSONView register(@ModelAttribute CompanyRegister companyDTO,BindingResult bind)
	{
		String validate = companyDTO.validate();
		if(!"success".equals(validate))
		{
			FailedJSONView view = new FailedJSONView();
			view.setError(validate);
			return view;
		}
		Company company = parseCompany(companyDTO);
		User admin = parseUser(companyDTO);
		
		CompanyService service = new CompanyService();

		boolean result = service.addCompany(company,admin);
		if(result)
		{
			SuccessJSONView view = new  SuccessJSONView();
			view.setPayload("success");
			return view;
		}else
		{
			FailedJSONView view = new FailedJSONView();
			view.setError("internal error when add company");
			return view;
		}
	}
	private Company parseCompany(CompanyRegister register)
	{
		Company company = new Company();
		company.setName(register.getCompany_name());
		company.setAddress(register.getProvince()+register.getCity()+register.getDistinguish()+register.getDetailAddress());
		company.setPhone(register.getCompany_phone());
		return company;
	}
	private User parseUser(CompanyRegister register)
	{
		User user = new User();
		user.setAccountType(AccountType.Supervisor);
		user.setName(register.getAdmin_name());
		user.setPassword(register.getAdmin_password());
		user.setEmail(register.getAdmin_email());
		user.setStatus(AccountStatus.InActive);
		user.setDisplay(register.getAdmin_display());
		return user;
	}
}
